package com.nwpu.coursesupport.service.imple;


import com.nwpu.coursesupport.criteria.ClassStudentSearchCriteria;
import com.nwpu.coursesupport.entity.Class;
import com.nwpu.coursesupport.entity.*;
import com.nwpu.coursesupport.entity.bean.Response;
import com.nwpu.coursesupport.entity.params.FinalExamTaskSubmit.CourseTargetParam;
import com.nwpu.coursesupport.entity.params.FinalExamTaskSubmit.FinalExamTaskSubmitParam;
import com.nwpu.coursesupport.entity.params.FinalExamTaskSubmit.ScoreItemJsonParam;
import com.nwpu.coursesupport.entity.params.FinalExamTaskSubmit.ScoreItemParam;
import com.nwpu.coursesupport.entity.params.SelectStudentParam;
import com.nwpu.coursesupport.entity.params.StudentInfo;
import com.nwpu.coursesupport.entity.params.correctTask.FinalTaskParam;
import com.nwpu.coursesupport.entity.params.correctTask.ScoreItem;
import com.nwpu.coursesupport.mapper.*;
import com.nwpu.coursesupport.tool.JSONUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shun
 * @email ws2017303035@mail.nwpu.edu.cn
 * @date 2020-08-04 21:33:50
 */
@Service
public class FinalExamTaskService {
    @Autowired
    private FinalExamTaskDao finalExamTaskDao;


    public Response submitFinalExamTask(List<FinalExamTaskSubmitParam> finalExamTaskSubmitParamList) {
        //判断是否为空
        if (CollectionUtils.isEmpty(finalExamTaskSubmitParamList)) {
            return Response.fail("您还未填写数据！");
        }
        //删除原有的
        Integer courseId = finalExamTaskSubmitParamList.get(0).getCourseId();
        List<FinalExamTaskEntity> finalExamTaskEntities = finalExamTaskDao.findByCourseId(courseId);
        for (FinalExamTaskEntity finalExamTaskEntity : finalExamTaskEntities) {
            finalExamTaskDao.deleteById(finalExamTaskEntity.getId());

            List<ScoreItemEntity> scoreItemEntities = scoreItemDao.findByFinalExamTaskId(finalExamTaskEntity.getId());

            List<FinalExamTaskCourseTargetEntity> finalExamTaskCourseTargetEntities =
                    finalExamTaskCourseTargetDao.findByFinalExamTaskId(finalExamTaskEntity.getId());

            List<StudentFinalExamScoreEntity> studentFinalExamScoreEntities = studentFinalExamScoreDao.findByFinalExamTaskId(finalExamTaskEntity.getId());

            if (!CollectionUtils.isEmpty(scoreItemEntities))
                for (ScoreItemEntity scoreItemEntity : scoreItemEntities) {
                    scoreItemDao.deleteById(scoreItemEntity.getId());
                }
            if (!CollectionUtils.isEmpty(finalExamTaskCourseTargetEntities))
                for (FinalExamTaskCourseTargetEntity finalExamTaskCourseTargetEntity : finalExamTaskCourseTargetEntities) {
                    finalExamTaskCourseTargetDao.deleteById(finalExamTaskCourseTargetEntity.getId());
                }
            if (!CollectionUtils.isEmpty(studentFinalExamScoreEntities))
                for (StudentFinalExamScoreEntity studentFinalExamScoreEntity : studentFinalExamScoreEntities) {
                    studentFinalExamScoreDao.deleteById(studentFinalExamScoreEntity.getId());
                }

        }


        //校验数据并存入数据库
        if (!CollectionUtils.isEmpty(finalExamTaskSubmitParamList))
            for (FinalExamTaskSubmitParam finalExamTaskSubmitParam : finalExamTaskSubmitParamList) {
                String titleNum = finalExamTaskSubmitParam.getTitleNum();
                if (titleNum == null || titleNum.equals("")) {
                    continue;
                }

                //判断课程目标权重和为1
                List<CourseTargetParam> courseTargetParams = finalExamTaskSubmitParam.getCourseTargets();
                Float total = new Float(0);
                for (CourseTargetParam courseTargetParam : courseTargetParams) {
                    total += courseTargetParam.getWeight();
                    System.out.println("3333:" + courseTargetParam.getWeight());
                    System.out.println("total:" + total);
                }
                if (total.compareTo(new Float(1)) != 0) {
                    return Response.fail("课程目标权重和不为1");
                }
                //非选择题，判断评分标准和分数加起来是不是等于满分
                if (!finalExamTaskSubmitParam.getIsSelect()) {
                    BigDecimal fullMark = finalExamTaskSubmitParam.getFullMark();
                    BigDecimal actualFullMark = new BigDecimal(0);
                    List<ScoreItemParam> scoreItemParams = finalExamTaskSubmitParam.getScoreItems();
                    if (CollectionUtils.isEmpty(scoreItemParams)) return Response.fail("您还未添加课程目标");
                    for (ScoreItemParam scoreItemParam : scoreItemParams) {
                        actualFullMark = actualFullMark.add(scoreItemParam.getFullMark());
                    }
                    if (actualFullMark.compareTo(fullMark) != 0) {
                        return Response.fail("评分标准总分不等于满分");
                    }
                }
                //存数据库
                //题目
                FinalExamTaskEntity finalExamTaskEntity = new FinalExamTaskEntity();
                finalExamTaskEntity.setIsSelect(finalExamTaskSubmitParam.getIsSelect());
                finalExamTaskEntity.setCourseId(finalExamTaskSubmitParam.getCourseId());
                finalExamTaskEntity.setSelectAnswer(finalExamTaskSubmitParam.getSelectAnswer());
                finalExamTaskEntity.setTitleNum(finalExamTaskSubmitParam.getTitleNum());
                finalExamTaskEntity.setFullMark(finalExamTaskSubmitParam.getFullMark().doubleValue());
                finalExamTaskDao.save(finalExamTaskEntity);
                Integer id = finalExamTaskEntity.getId();
                System.out.println("ID为：" + id);
                //非选择题，保存评分标准
                if (!finalExamTaskSubmitParam.getIsSelect()) {
                    List<ScoreItemParam> scoreItemParams = finalExamTaskSubmitParam.getScoreItems();
                    for (ScoreItemParam scoreItemParam : scoreItemParams) {
                        ScoreItemEntity scoreItemEntity = new ScoreItemEntity();
                        scoreItemEntity.setDescription(scoreItemParam.getDescription());
                        scoreItemEntity.setFinalExamTaskId(id);
                        scoreItemEntity.setFullMark(scoreItemParam.getFullMark().doubleValue());
                        scoreItemDao.save(scoreItemEntity);
                    }
                }
                //保存课程目标
                for (CourseTargetParam courseTargetParam : courseTargetParams) {
                    FinalExamTaskCourseTargetEntity finalExamTaskCourseTargetEntity = new FinalExamTaskCourseTargetEntity();
                    finalExamTaskCourseTargetEntity.setFinalExamTaskId(id);
                    finalExamTaskCourseTargetEntity.setFullMark(finalExamTaskSubmitParam.getFullMark().doubleValue());
                    finalExamTaskCourseTargetEntity.setCourseTargetId(courseTargetParam.getCourseTargetId());
                    finalExamTaskCourseTargetEntity.setWeight(courseTargetParam.getWeight().floatValue());
                    finalExamTaskCourseTargetDao.save(finalExamTaskCourseTargetEntity);
                }
                //保存学生得分表
                List<Student> students = new ArrayList<Student>();//该课程的所有学生
                List<Class> classList = classMapper.findByCourseId(finalExamTaskSubmitParam.getCourseId());
                for (Class class1 : classList) {
                    ClassStudentSearchCriteria cs = new ClassStudentSearchCriteria();
                    cs.setClassId(class1.getId());
                    List<Student> studentList = classStudentMapper.findStudentByParam(cs);
                    students.addAll(studentList);
                }
                for (Student student : students) {
                    StudentFinalExamScoreEntity studentFinalExamScoreEntity = new StudentFinalExamScoreEntity();
                    studentFinalExamScoreEntity.setStudentId(student.getId());
                    studentFinalExamScoreEntity.setFinalExamTaskId(id);
                    studentFinalExamScoreEntity.setFullMark(finalExamTaskSubmitParam.getFullMark().doubleValue());
                    studentFinalExamScoreEntity.setIsSelect(finalExamTaskSubmitParam.getIsSelect());
                    studentFinalExamScoreEntity.setSelectedAnswer(null);

                    List<ScoreItemParam> scoreItemParams = finalExamTaskSubmitParam.getScoreItems();
                    ArrayList<ScoreItemJsonParam> scoreItemJsonParams = new ArrayList<>();
                    for (ScoreItemParam scoreItemParam : scoreItemParams) {
                        ScoreItemJsonParam scoreItemJsonParam = new ScoreItemJsonParam();
                        scoreItemJsonParam.setActualMark(null);
                        scoreItemJsonParam.setFullMark(scoreItemParam.getFullMark());
                        scoreItemJsonParam.setDescription(scoreItemParam.getDescription());
                        scoreItemJsonParams.add(scoreItemJsonParam);
                    }
                    studentFinalExamScoreEntity.setScoreItem(JSONUtils.obj2json(scoreItemJsonParams));
                    studentFinalExamScoreDao.save(studentFinalExamScoreEntity);
                }


            }


        return Response.ok(null);

    }

    @Autowired
    private ScoreItemDao scoreItemDao;
    @Autowired
    private FinalExamTaskCourseTargetDao finalExamTaskCourseTargetDao;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private ClassStudentMapper classStudentMapper;
    @Autowired
    private StudentFinalExamScoreDao studentFinalExamScoreDao;

    public Response getFinalExamTask(Integer courseId) {
        List<FinalExamTaskEntity> finalExamTaskEntities = finalExamTaskDao.findByCourseId(courseId);
        ArrayList<FinalExamTaskSubmitParam> result = new ArrayList<>();
        for (FinalExamTaskEntity finalExamTaskEntity : finalExamTaskEntities) {
            FinalExamTaskSubmitParam finalExamTaskSubmitParam = new FinalExamTaskSubmitParam();
            finalExamTaskSubmitParam.setCourseId(courseId);
            finalExamTaskSubmitParam.setSelectAnswer(finalExamTaskEntity.getSelectAnswer());
            finalExamTaskSubmitParam.setTitleNum(finalExamTaskEntity.getTitleNum());
            finalExamTaskSubmitParam.setIsSelect(finalExamTaskEntity.getIsSelect());
            finalExamTaskSubmitParam.setFullMark(new BigDecimal(finalExamTaskEntity.getFullMark()));

            ArrayList<ScoreItemParam> scoreItems = new ArrayList<>();
            ArrayList<CourseTargetParam> courseTargets = new ArrayList<>();
            List<ScoreItemEntity> scoreItemEntities = scoreItemDao.findByFinalExamTaskId(finalExamTaskEntity.getId());
            for (ScoreItemEntity scoreItemEntity : scoreItemEntities) {
                ScoreItemParam scoreItemParam = new ScoreItemParam();
                scoreItemParam.setDescription(scoreItemEntity.getDescription());
                scoreItemParam.setFullMark(new BigDecimal(scoreItemEntity.getFullMark()));
                scoreItems.add(scoreItemParam);
            }
            List<FinalExamTaskCourseTargetEntity> courseTargetEntities = finalExamTaskCourseTargetDao.findByFinalExamTaskId(finalExamTaskEntity.getId());
            int i = 1;
            for (FinalExamTaskCourseTargetEntity courseTargetEntity : courseTargetEntities) {
                CourseTargetParam courseTargetParam = new CourseTargetParam();
                courseTargetParam.setCourseTargetId(courseTargetEntity.getCourseTargetId());
                courseTargetParam.setCourseTargetNum("课程目标" + i);
                courseTargetParam.setWeight(courseTargetEntity.getWeight());
                System.out.println("111:" + courseTargetEntity.getWeight());
                courseTargets.add(courseTargetParam);
                i++;
            }
            finalExamTaskSubmitParam.setScoreItems(scoreItems);
            finalExamTaskSubmitParam.setCourseTargets(courseTargets);
            result.add(finalExamTaskSubmitParam);

        }
        return Response.ok(result);
    }

    public Response selectStudent(Integer courseId) {
        ArrayList<SelectStudentParam> result = new ArrayList<>();
        List<Class> classes = classMapper.findByCourseId(courseId);
        for (Class aClass : classes) {
            SelectStudentParam selectStudentParam = new SelectStudentParam();
            selectStudentParam.setLabel(aClass.getName());
            selectStudentParam.setValue(aClass.getId());
            ArrayList<StudentInfo> studentInfos = new ArrayList<>();
            ClassStudentSearchCriteria cs = new ClassStudentSearchCriteria();
            cs.setClassId(aClass.getId());
            List<Student> students = classStudentMapper.findStudentByParam(cs);
            for (Student student : students) {
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setValue(student.getStudentCode());
                studentInfo.setLabel(student.getStudentCode() + "-" + student.getName());
                studentInfos.add(studentInfo);
            }
            selectStudentParam.setChildren(studentInfos);
            result.add(selectStudentParam);
        }
        return Response.ok(result);
    }

    @Autowired
    private StudentMapper studentMapper;

    public Response getStudentSubmitScore(String studentCode) throws Exception {
        ArrayList<FinalTaskParam> result = new ArrayList<>();

        int studentId = studentMapper.findByStudentCode(studentCode).getId();

        List<StudentFinalExamScoreEntity> studentFinalExamScoreEntities =
                studentFinalExamScoreDao.findByStudentId(studentId);
        for (StudentFinalExamScoreEntity studentFinalExamScoreEntity : studentFinalExamScoreEntities) {
            FinalTaskParam item = new FinalTaskParam();
            item.setStudentFinalExamScoreId(studentFinalExamScoreEntity.getId());
            item.setStudentId(studentId);
            FinalExamTaskEntity task = finalExamTaskDao.findById(studentFinalExamScoreEntity.getFinalExamTaskId());
            item.setTitleNum(task.getTitleNum());
            item.setFullMark(studentFinalExamScoreEntity.getFullMark());
            item.setAnswer(task.getSelectAnswer());
            item.setIsSelect(studentFinalExamScoreEntity.getIsSelect());
            item.setSelectedAnswer(studentFinalExamScoreEntity.getSelectedAnswer());
            ArrayList<ScoreItem> scoreItems = new ArrayList<>();

            String scoreItem = studentFinalExamScoreEntity.getScoreItem();
            List<ScoreItemJsonParam> scoreItemJsonParams = JSONUtils.json2list(scoreItem, ScoreItemJsonParam.class);
            for (ScoreItemJsonParam scoreItemJsonParam : scoreItemJsonParams) {
                ScoreItem scoreItem1 = new ScoreItem();
                scoreItem1.setDescription(scoreItemJsonParam.getDescription());
                if (scoreItemJsonParam.getActualMark() != null)
                    scoreItem1.setActualMark(scoreItemJsonParam.getActualMark());
                if (scoreItemJsonParam.getFullMark() != null)
                    scoreItem1.setFullMark(scoreItemJsonParam.getFullMark());
                scoreItems.add(scoreItem1);
            }

            item.setScoreItems(scoreItems);
            result.add(item);
        }
        return Response.ok(result);


    }

    public Response submitStudentScore(FinalTaskParam finalTaskParam) {
        System.out.println("收到：："+finalTaskParam);
        List<ScoreItem> scoreItems = finalTaskParam.getScoreItems();

        //非选择题，判断得分不能大于满分
        BigDecimal score = new BigDecimal(0f);
        if (!finalTaskParam.getIsSelect()) {
            for (ScoreItem scoreItem : scoreItems) {
                if (scoreItem.getActualMark() != null && scoreItem.getFullMark() != null) {
                    int i = scoreItem.getActualMark().compareTo(scoreItem.getFullMark());
                    if (i > 0) {
                        return Response.fail("得分不能大于满分");
                    }
                    score = score.add(scoreItem.getActualMark());
                }
            }

        }
        StudentFinalExamScoreEntity entity =
                studentFinalExamScoreDao.findById(finalTaskParam.getStudentFinalExamScoreId());

        if (finalTaskParam.getIsSelect()) {
            if (finalTaskParam.getAnswer().equals(finalTaskParam.getSelectedAnswer())) {
                entity.setActualMark(Float.parseFloat(entity.getFullMark() + ""));
            } else {
                entity.setActualMark(0f);
            }
            entity.setSelectedAnswer(finalTaskParam.getSelectedAnswer());
        } else {
            entity.setActualMark(score.floatValue());
            entity.setScoreItem(JSONUtils.obj2json(finalTaskParam.getScoreItems()));
        }

        studentFinalExamScoreDao.updateById(entity);
        return Response.ok(null);
    }
}

